import sys
from PySide2.QtWidgets import QTextBrowser, QApplication
from PySide2.QtCore import QObject, Signal
from PySide2.QtGui import QTextCursor


class EmittingStream(QObject):
    textWritten = Signal(str)

    def __init__(self):
        super(EmittingStream, self).__init__()

    def write(self, text):
        self.textWritten.emit(str(text))

class ConsoleWidget(QTextBrowser):

    def __init__(self):
        super(ConsoleWidget, self).__init__()
        # 重定向输出
        # emit = EmittingStream()
        # emit.textWritten.connect(self.normalOutputWritten)
        # sys.stdout = emit
        # sys.stderr = emit

    def __del__(self):
        pass
        # sys.stdout = sys.__stdout__
        # sys.stderr = sys.__stderr__

    def normalOutputWritten(self, text):
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.End)
        cursor.insertText(text)
        self.setTextCursor(cursor)
        self.ensureCursorVisible()

    def normalOutputWarp(self, text):
        text += "\n"
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.End)
        cursor.insertText(text)
        self.setTextCursor(cursor)
        self.ensureCursorVisible()
